<?php
/////////////////////////////////////////////////////////////////////////////
// 
//
// workflow_system
//
// workflow_copyright
// 
/////////////////////////////////////////////////////////////////////////////

/**
 * FILE_NAME : common.class.php   FILE_PATH : classes\libraries\common.class.php
 * 通用方法
 *
 * @copyright workflow_system 
 * @author workflow Develop Team 
 * @package 
 * @subpackage 
 * @version Wed Aug 08 15:34:14 CST 2007
 */

/*
+------------------------------------------------------------------------------------------------------
|   功能说明： 根据类表生成树型图.
|   调用部分 ：
|   ========================================
|
|	Common::remote_file_exists("http://www.baidu.com/rss");
|
+------------------------------------------------------------------------------------------------------
*/
class Common{

	/*
	函数：remote_file_exists
	功能：判断远程文件是否存在
	参数： $url_file - 远程文件URL
	返回：存在返回true，不存在或者其他原因返回false
	*/
	function remote_file_exists($url_file){
		//检测输入
		$url_file = trim($url_file);
		if (empty($url_file)) { return false; }
		$url_arr = parse_url($url_file);
		if (!is_array($url_arr) || empty($url_arr)){ return false; }

		//获取请求数据
		$host = $url_arr['host'];
		$path = $url_arr['path'] ."?". $url_arr['query'];
		$port = isset($url_arr['port']) ? $url_arr['port'] : "80";

		//连接服务器
		$fp = fsockopen($host, $port, $err_no, $err_str, 30);
		if (!$fp){ return false; }

		//构造请求协议
		$request_str = "GET ".$path." HTTP/1.1\r\n";
		$request_str .= "Host: ".$host."\r\n";
		$request_str .= "Connection: Close\r\n\r\n";

		//发送请求
		fwrite($fp, $request_str);
		$first_header = fgets($fp, 1024);
		fclose($fp);

		//判断文件是否存在
		if (trim($first_header) == ""){ return false; }
		if (!preg_match("/200/", $first_header)){
			return false;
		}
		return true;
	}


	/**
	 * 对抛出的变量进行转义修理
	 *
	 * @param string $varstring
	 * @param var $var
	 */
	function stripslashes_array($var){
		if (!get_magic_quotes_gpc()){
			$value = $var;
		}else{
			$value = is_array($var)?array_map(array('Common', 'stripslashes_array'), $var) :stripslashes($var);
		}
		return $value;
	}

	/**
	 * 对入库的变量进行转义修理
	 *
	 * @param string $varstring
	 * @param var $var
	 */
	function addslashes_array($var){
		$value = is_array($var)?array_map(array('Common', 'addslashes_array'), $var) :(!get_magic_quotes_gpc()?addslashes(trim($var)):trim($var));
		return $value;
	}
	
	/**
	 * 根据系统魔术符号情况返回对应的值。这里主要是为了写商品分类文件而做的。
	 * 
	 * @author     
	 * @param  
	 * @return int/bool/object/array
	 */
	function magic_value($var){
		if (!is_array($var) && !get_magic_quotes_gpc()){
			$value	= addslashes($var);
		}else{
			$value  = str_replace("\'","'",$var);
			$value  = str_replace("'","\'",$value);
		}
		return $value;
	}

	/**
	 * POST及COOKIE数组中元素的转义
	 *
	 * @param string[] $array
	 * @return array[]
	 */
	function input_addslashes_array($array) {
		if (!empty($array)){
			while (list($k,$v) = each($array)) {
				if (is_string($v)) {
					if (!get_magic_quotes_gpc()){
						$array[$k] = addslashes(trim($v));
					}else {
						$array[$k] = trim($v);
					}
				} else if (is_array($v))  {
					$array[$k] = Common::addslashes_array($v);
				}
			}
			return $array;
		}
	}

	/**
	 * 将GET数组中元素的转义,并限定参数中不能存在敏感参数
	 *
	 * @param string[] $array
	 * @return array[]
	 */
	function input_addslashes_for_get_array($array) {
		if (!empty($array)){
			while (list($k,$v) = each($array)) {
				if (is_string($v)) {
					if (!preg_match("/SELECT|UNION|DESCRIBE|EXPLAIN|SCRIPT/i", strtoupper($v))) {
						if (!get_magic_quotes_gpc()){
							$array[$k] = addslashes(trim($v));
						}else {
							$array[$k] = trim($v);
						}
	//					$array[$k] = addslashes(trim($v));
					}else{
						echo "参数有非法字符!";exit;
					}
				} else if (is_array($v))  {
					$array[$k] = Common::input_addslashes_for_get_array($v);
				}
			}
			return $array;
		}else {
			return false;
		}
	}
	/**
	 * 显示信息
	 *
	 * @param int $genre 信息类型:1错误2成功3提醒
	 * @param string $message 信息内容
	 * @param int $isback 是否需要back 1是back0是跳转
	 */
	function showMessage($genre,$message,$url="",$isback=0){
		global $INFO;
		if($url == ""){
			$url = $_COOKIE["backurl"];

		}
		else if (substr($url,0,7) != "http://"){
			$url = $INFO[site_url] . "/" . $url;
		}
		/*
		@header("Location:" . $INFO[site_url] . "showMessage.php?message=" . urlencode($message) . "&genre=" . $genre . "&url=" . urlencode($url));
		*/
		echo "<script language='javascript'>";
		echo "alert('" . $message . "');";
		if ($isback==0)
		echo "location.href='" . $url . "';";
		else
		echo "window.history.back(-1);";
		echo "</script>";
		exit;
	}

	/**
	 * 显示二维数组单选框/复选框
	 *
	 * @param string $formname 表单名称
	 * @param string $formid 表单ID
	 * @param var[] $array 表单值和文本的数组
	 * @param string $key_value value中值的下标
	 * @param string $display_value 显示值的下标
	 * @param var $checkvalue 被选择的值
	 * @param var $formgenre 表单类型
	 * @return string
	 * 调用例子 $obj->showForm_Radio('rdogender','',$cfg_gender,1)
	 */
	function showForm_Radio_Array($formname,$formid,$array='',$key_value,$display_value,$checkvalueArray=array(),$formgenre='radio'){
		if (!is_array($array)){
			return false;
		}
		$radiolist = '';
		if ($formgenre != "radio" && $formgenre != "checkbox"){
			return false;
		}
		foreach($array as $k=>$v){
			$radiolist .= "<input type='" . $formgenre . "' name='" . $formname . "' class='input_radio'";
			if ($formid=='')
			$formid = $formname;
			$radiolist .= " id='" . $formid . $k . "' value='" . $v[$key_value] . "'";
			if (is_array($checkvalueArray))
			foreach($checkvalueArray as $c=>$d){
				if ($d!="" && $d == $v[$key_value])
				$radiolist .= " checked ";
			}
			$radiolist .= "><label for='" . $formid . $k . "'>" . $v[$display_value] . "</label>";
		}
		return $radiolist;
	}

	/**
	 * 显示单选框/复选框
	 *
	 * @param string $formname 表单名称
	 * @param string $formid 表单ID
	 * @param var[] $array 表单值和文本的数组，KEY为值，VALUE为文本
	 * @param var $checkvalue 被选择的值
	 * @param var $formgenre 表单类型
	 * @param var $eventstring 事件字符串
	 * @return string
	 * 调用例子 $obj->showForm_Radio('rdogender','',$cfg_gender,1)
	 */
	function showForm_Radio($formname,$formid,$array,$checkvalue='',$formgenre='radio',$eventstring=''){
		$radiolist = '';
		if ($formgenre != "radio" && $formgenre != "checkbox"){
			return false;
		}
		foreach($array as $k=>$v){
			$radiolist .= "<input type='" . $formgenre . "' name='" . $formname . "' class='input_radio'";
			if ($formid=='')
			$formid = $formname;
			$radiolist .= " id='" . $formid . "_" . $k . "' value='" . $k . "'";

			if(is_array($checkvalue)){
				foreach($checkvalue as $c=>$d){
					if ($d!="" && $d == $k)
					$radiolist .= " checked ";
				}
			}else{
				if ($checkvalue!="" && $checkvalue == $k)
				$radiolist .= " checked ";
			}
			$radiolist .= $eventstring."><label for='" . $formid . "_" . $k  ."'>" . $v . "</label> ";
		}
		return $radiolist;
	}

	/**
	 * 显示下拉框
	 *
	 * @param string $formname 表单名称
	 * @param string $formid 表单ID
	 * @param string $eventstring 事件字符串
	 * @param var[] $array 表单值和文本的数组，KEY为值，VALUE为文本
	 * @param var $selectvalue 被选择的值
	 * $@param string $option_select_array 如果有值的话会出现一个<option value='$option_select_array['value''>$option_select_array['text']</option>的选项
	 * @return string
	 * 调用例子 $obj->showForm_Select('slcedu','','',$cfg_education,1)
	 */
	function showForm_Select($formname,$formid,$eventstring,$array,$selectvalue='',$option_select_array=''){
		if (!is_array($array)){
			return '';
		}
		$selectlist = '';
		$selectlist .= "<select name='" . $formname . "'";
		if ($formid == ''){
			$formid = $formname;
		}
		$selectlist .= " id='" . $formid . "' " . $eventstring . ">\n";
		if (is_array($option_select_array)){
			$selectlist .= "<option value='" . $option_select_array['value'] . "'>" . $option_select_array['text'] . "</option>";
		}
		foreach ($array as $k=>$v){
			$selectlist .= "<option value='" . $k . "'";
			if ($selectvalue!="" && $selectvalue == $k){
				$selectlist .= " selected";
			}
			$selectlist .= ">" . $v . "</option>\n";
		}
		$selectlist .= "</select>";
		return $selectlist;
	}

	/**
	 * 显示下拉框2
	 *
	 * @param string $formname 表单名称
	 * @param string $formid 表单ID
	 * @param string $eventstring 事件字符串
	 * @param var[] $array 表单值和文本的数组，KEY为值，VALUE为文本
	 * @param var $selectvalue 被选择的值
	 * @param var $style 菜单样式
	 * @return string
	 * 调用例子 $obj->showForm_Select('slcedu','','',$cfg_education,1)
	 */
	function showForm_Select2($formname,$formid,$eventstring,$array,$selectvalue='',$style=''){
		$lang_obj = new FrameWork();
		$lang_obj->setFrameWork();
		$lang_obj->getlang("sys_common");
		$selectlist = '';
		$selectlist .= "<select class='" . $style . "' name='" . $formname . "'";
		if ($formid == ''){
			$formid = $formname;
		}
		$selectlist .= " id='" . $formid . "' " . $eventstring . ">\n";
		$selectlist .= "<option value='0'>" . $lang_obj->_lang['langSysCPleaseSelect'] . "</option>\n";
		if (is_array($array)){
			foreach ($array as $k=>$v){
				$selectlist .= "<option value='" . $v[id] . "'";
				if ($selectvalue!="" && $selectvalue == $v[id]){
					$selectlist .= " selected";
				}
				$selectlist .= ">" . $v[name] . "</option>\n";
			}
		}
		$selectlist .= "</select>";
		unset($lang_obj);
		return $selectlist;
	}

	/**
	 * 得到图片缩略图的名称/路径
	 *
	 * @param string $filename
	 * @return string/bool
	 */
	function getSmallPicName($filename){
		$nameArray = explode(".",$filename);
		if (count($nameArray)>=2){
			$nameArray[count($nameArray)-2] .= "_small";
			return implode(".",$nameArray);
		}
		else
		return false;
	}

	/**
	 * 加密
	 *
	 * @param string $start 需要加密的字符串
	 * @return string
	 */
	function mycrpyt($start)
	{
		if($start=='') return;
		$start=strrev($start);
		$sRet=base64_encode($start);
		return $sRet;
	}

	/**
	 * 解密
	 *
	 * @param string $start 需要解密的字符串
	 * @return string
	 */
	function myuncrpyt($start)
	{
		$sRet='';
		$sRet=base64_decode($start);
		$sRet=strrev($sRet);
		return $sRet;
	}


	/**
	 * 得到一个形式为：array(array('1'=>'产品'))的数组，一般用在数据库中得到的数组，整理为select下拉框函数可以用的格式数组
	 *
	 * @param var[] $input_array
	 * @param var[] $field_array 0为value  1为text
	 * @return var[]
	 */
	function getSelectArray($input_array,$field_array){
		$result = array();
		if (is_array($input_array)){
			foreach ($input_array as $key => $value) {
				$key = $value[$field_array[0]];
				$result[$key] = $value[$field_array[1]];
			}
		}
		return $result;
	}

	/**
	 * 将数组里的相应键值替换为特有的值
	 *
	 * @param var[] $array  需要替换的数组
	 * @param string $field_name  需要被替换的健名
	 * @param var[] $config_array  替换的数组
	 * @return var[]
	 */
	function replaceArrayLang($array,$field_name,$config_array){
		if (is_array($array)){
			foreach ($array as $key=>$value){
				foreach($value as $k=>$v){
					if ($field_name == $k){
						$array[$key][$k] = $config_array[$v];
					}
				}
			}
		}
		return $array;
	}
	/**
	 * 替换换行符
	 *
	 * @param string $str
	 * @return string
	 */
	function replacebr($str){
		$str = str_replace(chr(10),'',$str);
		$str = str_replace(chr(13),'',$str);
		$str = str_replace(chr(9),'',$str);
		$str = str_replace(chr(11),'',$str);
		return $str;
	}

	/**
	 * 替换换行(\n,\f)为<br>
	 *
	 * @param string $str
	 * @return string
	 */
	function replaceToBr($str){
		$str = str_replace(array(chr(10),chr(13)),array('<br>'),$str);
		return $str;
	}
	/**
	 * 计算日期函数
	 * Inetrval 要添加的时间间隔字符串表达式，具体参数如下：  
	 * 		y year 年
	 * 		q Quarter 季度
	 * 		m Month 月
	 * 		d Day 天
	 * 		w Week 星期
	 * 		h Hour 小时
	 * 		n Minute 分
	 * 		s Second 秒
	 * number 要添加的时间间隔的个数的数值表达式；
	 * Date表示日期；
	 * @param string $interval
	 * @param int $number
	 * @param timestamp $datetime
	 * @return timestamp
	 */
	function calculateDate($interval, $number, $datetime){
		$date_time_array = getdate($datetime);
		$hours = $date_time_array["hours"];
		$minutes = $date_time_array["minutes"];
		$seconds = $date_time_array["seconds"];
		$month = $date_time_array["mon"];
		$day = $date_time_array["mday"];
		$year = $date_time_array["year"];
		switch ($interval) {
			case "y": $year += $number; break;
			case "q": $month += ($number*3); break;
			case "m": $month += $number; break;
			case "d": $day += $number; break;
			case "w": $day += ($number*7); break;
			case "h": $hours += $number; break;
			case "i": $minutes += $number; break;
			case "s": $seconds += $number; break;
		}
		$timestamp = mktime($hours ,$minutes, $seconds, $month, $day, $year);
		return $timestamp;
	}
	/**
	 * 生成随机字符串
	 *
	 * @param array $chars		随机字符数组
	 * @param int $len 			生成的随机字符长度
	 * @return string $output 	返回随机字符串
	 */
	function genRandomString($chars='', $len)
	{
		if ($chars == ''){
			$chars = array(
			"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k",
			"l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v",
			"w", "x", "y", "z"
			);
		}
		if (!is_array($chars) && $chars != ""){
			$clen = strlen($chars);
			for($i=0;$i<$clen;$i++){
				$chars_array[$i] = substr($chars,$i,1);
			}
			$chars = $chars_array;
		}
		$chars_len = count($chars) - 1;
		shuffle($chars);
		$output = "";
		for ($i=0; $i<$len; $i++)
		{
			$output .= $chars[mt_rand(0, $chars_len)];
		}
		return $output;
	}

	/**
	 * 得到某文件夹中的内容
	 *
	 * @param string $dir
	 * @return var[]
	 */
	function getDirArray($dir = "../templates/storestyle"){
		$dh  = opendir($dir);
		while (false !== ($filename = readdir($dh))) {
			$files[] = $filename;
		}
		array_shift ($files);
		$templates = array();
		foreach ($files as $k=>$v){
			$pos = strpos($v, ".");
			if ($pos === false) {
				$templates[] = $v;
			}

		}
		$vi = 0;
		foreach ($templates as $k =>$v) {
			$Temp_array[$vi][file] = $v;
			$vi++;

		}

		return $Temp_array;
	}

	/**
	 * 将二维数组转为字符串
	 *
	 * @param var[] $arr 要转为字符串的二维数组
	 * @param string $key_char 键与值之间的分割
	 * @param string $value_char 数组单元之间的分割
	 * @return string
	 */
	function arrayToString($arr,$key_char = "==>",$value_char = "::"){
		$str = "";
		if (is_array($arr)){
			foreach ($arr as $k=>$v){
				$str .= $k . $key_char . $v . $value_char;
			}
			if (substr($str,strlen($str) - strlen($value_char)) == $value_char){
				$str = substr($str,0,strlen($str) - strlen($value_char));
			}
		}
		return $str;
	}

	/**
	 * 将内容里的{name}替换为数组里相应单元的值
	 *
	 * @param var[] $arr
	 * @param string $content 要替换的内容文字
	 */
	function replaceMailContent($arr,$content){

		if (is_array($arr)){
			foreach($arr as $k=>$v){
				if (is_array($content)){
					foreach ($content as $ck=>$cv){
						if (is_array($cv)){
							foreach ($cv as $seck=>$secv){
								$content[$ck][$seck] = str_replace("{" . $k . "}",$v,$secv);
							}
						}else{
							$content[$ck] = str_replace("{" . $k . "}",$v,$cv);
						}
					}
					//$str = $content;
				}else{
					$content = str_replace("{" . $k . "}",$v,$content);
				}
			}
		}
		return $content;
	}


	/**
	 * 根据数组里和权限有关的键，来输出符合的单元来
	 *
	 * @param var[] $arr
	 * @param string $key
	 * @param string $value
	 * @return var[]
	 */
	function getRightArray($arr,$key,$value){
		$i = 0;
		$value = intval($value);
		$newarr = array();
		if (is_array($arr)){
			foreach($arr as $k=>$v){
				if ($v[$key] <= $value && ($v[$key] != (0-$value) || $v[$key] == 0)){
					$newarr[$i] = $v;

				}
				if (is_array($v['baby'])){
					$newarr[$i]['baby'] = array();
					$j = 0;
					foreach($v['baby'] as $sk=>$sv){
						if ($sv[$key] <= $value && ($sv[$key] != (0-$value) || $sv[$key] == 0)){
							$newarr[$i]['baby'][$j] = $sv;
						}
						$j++;
					}
				}
				$i++;
			}
		}
		return $newarr;
	}


	/**
	 * TARGET菜单
	 *
	 * @param var[] $menu_name
	 */
	function getTargetMenu($menu_name = "",$web_url=""){
		include_once("xmlread.class.php");
		if ($web_url != '') {
			$cur_url = $web_url;
		}else {
			$cur_url = Common::getCurrUrl(1);
		}
		$hdc = new xmlRead('UTF-8',$node); //设置编码
		$hdc->var_use_iconv = 1;   //是否使用 iconv
		$hdc->xmlRead_node_config = "root";
		$hdc->xmlRead_parser_file(BasePath . "/config/" . "target_menu.php");
		$value = $hdc->xmlRead_get_ret(); //得到数组
		$value = $value['root']['group'];
		foreach ($value as $k=>$v){
			if (trim($v['name']) == $menu_name){
				$menu_array['body'] = $v['target'];
				foreach ($menu_array['body'] as $mk=>$mv){
					foreach ($mv as $k_=>$v_){
						$menu_array['body'][$mk][$k_] = Common::replacebr(trim($v_));
						$menu_array['body'][$mk][$k_] = Common::replaceMenuLang($menu_array['body'][$mk][$k_]);
					}
					if (trim($menu_array['body'][$mk]['link']) == trim($cur_url)){
						$menu_array['body'][$mk]['class']  = "selected";
					}
				}
				$menu_array['id'] = Common::replacebr($v['groupid']);
			}
		}
		//print_r($menu_array);
		return $menu_array;
	}

	/**
	 * 得到当前页面地址
	 *
	 * @param int $genre 类型 0完整路径1当前页面名称
	 * 
	 * @return string
	 */
	function getCurrUrl($genre = 0){
		$if_ajax = 0;

		if (is_array($_SERVER['argv'])){
			foreach ($_SERVER['argv'] as $v){
				/**
				 * 判断是否ajax访问，ajax访问不作为当前页面地址记录
				 */
				if(preg_match("/ajax=1$/",$v)){
					$if_ajax = 1;
				}
				$param .= $v . "&";
			}
		}
		/**
		 * ajax访问不作为当前页面地址记录，将上一页访问地址作为当前地址返回
		 */
		if($if_ajax == 1){
			$cur_url = $_SERVER['HTTP_REFERER'];
			return $cur_url;
		}

		if ($param != "" && substr($param,strlen($param)-1) == "&"){
			$param = substr($param,0,strlen($param)-1);
			$cur_url = "?" . $param;
		}

		if ($_SERVER['SERVER_PORT'] != "80"){
			$substr = ":" . $_SERVER['SERVER_PORT'];
		}

		if($genre == 0){
			$url = $_SERVER['SERVER_NAME'] . $substr . $_SERVER['PHP_SELF'] . $cur_url;
			$url = str_replace('//','/',$url);
			$cur_url = "http://" . $url;
		}else if($genre == 1){
			$cur_url = preg_replace("/(.*\/)(.*\.php)/",'\\2',$_SERVER['PHP_SELF']) . $cur_url;
			$cur_url = str_replace('//','/',$cur_url);
		}
		return $cur_url;
	}

	/**
	 * 获得客户端浏览器类型
	 *
	 * @return array (4 FF；5 IE；)
	 */
	function getClinetBrowser(){
		$lang_obj = new FrameWork();
		$lang_obj->setFrameWork();
		$lang_obj->getlang("sys_common");
		$Agent =   $_SERVER["HTTP_USER_AGENT"];
		$browser[0]   =   60;
		$browser[1]   =   $lang_obj->_lang['langSysCSealed'];

		if(strpos($Agent, "Mozilla")){
			$browser[0] = 1; $browser[1] = $lang_obj->_lang['langSysCSealed'];
		}
		if(strpos($Agent, "Mozilla/4")){
			$browser[0] = 1; $browser[1] = '4.0';
		}
		if(strpos($Agent, "Firebird")){
			$browser[0] = 1; $browser[1] = 'Firebird';
		}
		if(strpos($Agent, "Netscape")){
			$browser[0] = 2; $browser[1] = $lang_obj->_lang['langSysCSealed'];
		}
		if(strpos($Agent, "Netscape6/")){
			$browser[0] = 2; $browser[1] = '6.0';
		}
		if(strpos($Agent, "Netscape/7.1")){
			$browser[0] = 2; $browser[1] = '7.1';
		}
		if(strpos($Agent, "Opera")){
			$browser[0] = 3; $browser[1] = 'Opera';
		}
		if(strpos($Agent, "Firefox")){
			$browser[0] = 4; $browser[1] = 'Firefox';
		}
		if(strpos($Agent, "MSIE")){
			$browser[0] = 5; $browser[1] = $lang_obj->_lang['langSysCSealed'];
		}
		if(strpos($Agent, "MSIE 7.0")){
			$browser[0] = 5; $browser[1] = '7.0';
		}
		if(strpos($Agent, "MSIE 6.0")){
			$browser[0] = 5; $browser[1] = '6.0';
		}
		if(strpos($Agent, "MSIE 5.5")){
			$browser[0] = 5; $browser[1] = '5.5';
		}
		if(strpos($Agent, "MSIE 5.0")){
			$browser[0] = 5; $browser[1] = '5.0';
		}
		if(strpos($Agent, "MSIE 4.0")){
			$browser[0] = 5; $browser[1] = '4.0';
		}
		unset($lang_obj);
		return $browser;
	}

	/**
	 * 获取客户端操作系统
	 *
	 * @return array
	 */
	function GetClinetOS(){
		$Agent = $_SERVER["HTTP_USER_AGENT"];
		$os = 60;

		if (strpos($Agent, 'Win') && strpos($Agent, '95')){
			$os = 1;
		}
		elseif (strpos($Agent,'Win 9') && strpos($Agent, '4.90')){
			$os = 2;
		}
		elseif (strpos($Agent,'Win') && ereg($Agent, '98')){
			$os = 3;
		}
		elseif (strpos($Agent,'Win') && strpos($Agent, 'NT 5.0')){
			$os = 4;
		}
		elseif (strpos($Agent, 'Win') && strpos($Agent, 'NT 5.1')){
			$os = 5;
		}
		elseif (strpos($Agent, 'Win') && strpos($Agent, 'NT 5.2')){
			$os = 22;
		}
		elseif (strpos($Agent, 'Win') && strpos($Agent, 'NT')){
			$os = 6;
		}
		elseif (strpos($Agent, 'Win') && strpos($Agent, '32')){
			$os = 7;
		}
		elseif (strpos($Agent, 'Win')){
			$os = 8;
		}
		elseif (strpos($Agent, 'Linux')){
			$os = 9;
		}
		elseif (strpos($Agent, 'Unix')){
			$os = 10;
		}
		elseif (strpos($Agent, 'sun') && strpos($Agent, 'OS')){
			$os = 11;
		}
		elseif (strpos($Agent, 'IBM') && strpos($Agent, 'OS')){
			$os = 12;
		}
		elseif (strpos($Agent, 'Mac') && strpos($Agent, 'PC')){
			$os = 13;
		}
		elseif (strpos($Agent, 'PowerPC')){
			$os = 14;
		}
		elseif (strpos($Agent, 'AIX')){
			$os = 15;
		}
		elseif (strpos($Agent, 'HPUX')){
			$os = 16;
		}
		elseif (strpos($Agent, 'NetBSD')){
			$os = 17;
		}
		elseif (strpos($Agent, 'BSD')){
			$os = 18;
		}
		elseif (strpos($Agent, 'OSF1')){
			$os = 19;
		}
		elseif (strpos($Agent, 'IRIX')){
			$os = 20;
		}
		elseif (strpos($Agent, 'FreeBSD')){
			$os = 21;
		}
		return $os;
	}

	/**
	 * flash图片地址加密
	 *
	 * @param string $str
	 * @param string $key
	 * @return string
	 */
	function encodeStr($str, $key)
	{
		$len = strlen($str);
		$k = strlen($key);
		$rtn = array();
		for($i =0,$j = 0; $i < $len; $i ++){
			$rtn[] = chr(ord(substr($str,$i, 1)) ^ ord(substr($key,$j++,1)));
			if($j == $k)
			{
				$j = 0;
			}
		}
		$rtn = implode('', $rtn);
		$rtn = base64_encode($rtn);
		return $rtn;
	}
	/**
	 * flash图片地址解密
	 *
	 * @param string $str
	 * @param string $key
	 * @return string
	 */
	function decodeStr($str, $key) {
		$str = base64_decode($str);
		$len = strlen($str);
		$k = strlen($key);
		$rtn = array();
		$j = 0;
		$i = 0;
		for($i =0,$j = 0; $i < $len; $i ++){
			$rtn[] = chr(ord(substr($str,$i, 1)) ^ ord(substr($key,$j++,1)));
			if ($j >= $k) {
				$j = 0;
			}
		}
		$rtn = implode('', $rtn);
		return $rtn;
	}

	/**
	 * 截字
	 * @author 
	 * @param  
	 * @return string
	 */
	function cutstr($string, $length,$charset='utf-8', $dot = ' ...') {

		if(strlen($string) <= $length) {
			return $string;
		}

		$string = str_replace(array('&amp;', '&quot;', '&lt;', '&gt;'), array('&', '"', '<', '>'), $string);

		$strcut = '';
		if(strtolower($charset) == 'utf-8') {

			$n = $tn = $noc = 0;
			while($n < strlen($string)) {

				$t = ord($string[$n]);
				if($t == 9 || $t == 10 || (32 <= $t && $t <= 126)) {
					$tn = 1; $n++; $noc++;
				} elseif(194 <= $t && $t <= 223) {
					$tn = 2; $n += 2; $noc += 2;
				} elseif(224 <= $t && $t < 239) {
					$tn = 3; $n += 3; $noc += 2;
				} elseif(240 <= $t && $t <= 247) {
					$tn = 4; $n += 4; $noc += 2;
				} elseif(248 <= $t && $t <= 251) {
					$tn = 5; $n += 5; $noc += 2;
				} elseif($t == 252 || $t == 253) {
					$tn = 6; $n += 6; $noc += 2;
				} else {
					$n++;
				}

				if($noc >= $length) {
					break;
				}

			}
			if($noc > $length) {
				$n -= $tn;
			}

			$strcut = substr($string, 0, $n);

		} else {
			for($i = 0; $i < $length - strlen($dot) - 1; $i++) {
				$strcut .= ord($string[$i]) > 127 ? $string[$i].$string[++$i] : $string[$i];
			}
		}

		$strcut = str_replace(array('&', '"', '<', '>'), array('&amp;', '&quot;', '&lt;', '&gt;'), $strcut);

		return $strcut.$dot;
	}
	/**
	 * 整理文件大小显示
	 *
	 * @param int $filesize
	 * @return string
	 */
	function filesize($filesize) {
		if($filesize >= 1073741824) {
			$filesize = round($filesize / 1073741824 * 100) / 100 . ' GB';
		} elseif($filesize >= 1048576) {
			$filesize = round($filesize / 1048576 * 100) / 100 . ' MB';
		} elseif($filesize >= 1024) {
			$filesize = round($filesize / 1024 * 100) / 100 . ' KB';
		} else {
			$filesize = $filesize . ' Bytes';
		}
		return $filesize;
	}

	/**
	 * 得到某个菜单列表,最多2级
	 * 升级菜单方法，以前一个菜单项只能对应一个连接地址，但是现实中会有多个连接地址对应一个菜单项的选中，目前是在XML文件中的URL里用|分割，例如，<menu url="/member/own_shopproductcate.php|own_shopproduct.php?action=list&classid=*" id="">宝贝分类</menu>*代表任意数字或内容
	 *
	 * @param string $menu_array   菜单的数组
	 * @param var[] $web_url  网站地址
	 * 
	 * @return var[]
	 */
	function getMenu($menu_array,$web_url=""){
		//print_r($menu_array);
		$cur_url = Common::getCurrUrl();
		unset( $menu_array['_sys_'] );
		if (is_array($menu_array)){
			foreach ($menu_array as $k=>$v){
				if ($v['url'] != ""){
					$url_array = explode("|",$v['url']);
					if (strstr($v['url'],"http://")){
						$menu_array[$k]['url'] = $url_array[0];
						$menu_array[$k]['blank'] = 1;/*弹出页面*/
					}else {
						$menu_array[$k]['url'] = $web_url . $url_array[0];
					}
					foreach ($url_array as $uk=>$uv){
						if ($uv != ""){
							$uv = str_replace(".","\.",$uv);
							$uv = str_replace("/","\/",$uv);
							$uv = str_replace("?","\?",$uv);
							$uv = str_replace("=","\=",$uv);
							$uv = str_replace("*",".*",$uv);
							$uv = "/" . $uv . "/i";
							if (preg_match($uv,$cur_url)){
								$menu_array[$k]['class'] = 'selected';
							}
						}
					}
				}
				if (is_array($v['baby'])){
					foreach ($v['baby'] as $subk=>$subv){
						if ($subv['url'] != ""){
							$menu_array[$k]['baby'][$subk]['url'] = $web_url . $subv['url'];
							if ($cur_url == $menu_array[$k]['baby'][$subk]['url']){
								$menu_array[$k]['baby'][$subk]['class'] = 'selected';
							}
						}
					}
				}
			}
		}
		return $menu_array;
	}

	/**
	* JS编码转换escape
	* @author 
	* @param  $str 字符串 $char编码格式UTF-8或GBK
	* @return string
	*/
	function  unescape($str,$char)
	{
		if ($char == 'UTF-8'){//utf8格式
			$ret = '';
			$len = strlen($str);
			for ($i = 0; $i < $len; $i++){
				if ($str[$i] == '%' && $str[$i+1] == 'u'){
					$val = hexdec(substr($str, $i+2, 4));
					if ($val < 0x7f) $ret .= chr($val);
					else if($val < 0x800) $ret .= chr(0xc0|($val>>6)).chr(0x80|($val&0x3f));
					else $ret .= chr(0xe0|($val>>12)).chr(0x80|(($val>>6)&0x3f)).chr(0x80|($val&0x3f));
					$i += 5;
				}
				else if ($str[$i] == '%'){
					$ret .= urldecode(substr($str, $i, 3));
					$i += 2;
				}
				else $ret .= $str[$i];
			}
			return $ret;
		}elseif ($char == 'GBK'){
			$str = rawurldecode($str);
			preg_match_all("/%u.{4}|&#x.{4};|&#\d+;|&#\d+?|.+/U",$str,$r);
			$ar = $r[0];
			foreach($ar as $k=>$v) {
				if(substr($v,0,2) == "%u")
				$ar[$k] = mb_convert_encoding(pack("H4",substr($v,-4)),'GBK','UCS-2');
				elseif(substr($v,0,3) == "&#x")
				$ar[$k] = mb_convert_encoding(pack("H4",substr($v,3,-1)),'GBK','UCS-2');
				elseif(substr($v,0,2) == "&#") {
					$ar[$k] = mb_convert_encoding(pack("n",preg_replace("/[^\d]/","",$v)),'GBK','UCS-2');
				}
			}
			return join("",$ar);
//			return $str;
		}else {
			return false;
		}
	}
	
	/**
	 * js escape方式编码
	 * @author workflow Develop Team     
	 * @param  $str字符串，$char编码格式UTF-8或GBK
	 * @return string
	 */
	function escape($str,$char){
		if ($char == 'GBK'){
			preg_match_all("/[\x80-\xff].|[\x01-\x7f]+/",'请选择',$teststr);
		    $test = $teststr[0];
		    foreach($test as $k=>$v){
		        if(ord($ar[$k])>=127){
		            $testString=bin2hex(iconv("GBK","ucs-2",$v));
		            $reString.="%u".$testString;
		        } else {
		            $reString.= rawurlencode($v);
		        }
		    }
			if ($reString !== '%u8bf7%u9009%u62e9'){
				$sign = true;
			}
		    unset($teststr,$test,$testString,$reString);
			
			preg_match_all("/[\x80-\xff].|[\x01-\x7f]+/",$str,$newstr);
		    $ar = $newstr[0];
		    foreach($ar as $k=>$v){
		        if(ord($ar[$k])>=127){
		            $tmpString=bin2hex(iconv("GBK","ucs-2",$v));
		            if (!eregi("WIN",PHP_OS) && $sign==true){
		                $tmpString = substr($tmpString,2,2).substr($tmpString,0,2);
		            }
		            $reString.="%u".$tmpString;
		        } else {
		            $reString.= rawurlencode($v);
		        }
		    }
		    return $reString;
		}elseif ($char == 'UTF-8'){
			return $str;
		}
	}

	/**
	* 获得相关信息
	* @param  $type string , $info string ,  $level int 
	* @return bool
	*/
	function outMessage($type,$info,$level){
		switch ($type){
			case "json":
				Common::outJsonMessage($info,$level);
				break;
			default:
				Common::outJsonMessage($info,$level);
				break;

		}
	}


	/**
	* 显示可以被JSON解析的信息
	* @param  $info string ,  $level int 
	* @return string
	*/
	function outJsonMessage($info,$level){
		echo  "{type:".intval($level).",message:\"".$info."\"}";exit;
	}

	/**
	 * usort() 排序正序使用方法 usort($a,array("类名","方法名"));
	 * @author workflow Develop Team    
	 * @param  
	 * @return int/bool/object/array/string
	 */
	function cmp($a, $b)
	{
		if ($a == $b) {
			return 0;
		}
		return ($a < $b) ? -1 : 1;
	}

	/**
	 * 将菜单中{lang}替换为语言包中文字
	 *
	 * @param $langString
	 * @return string
	 */
	function replaceMenuLang($langString,$langType="zh-cn"){
		if (preg_match_all("|\{lang(.*)\}|U", $langString, $matches, PREG_SET_ORDER)){
			if(!is_object($this->obj_frameword)){
				require_once("framework.core.php");
				$this->obj_frameword = new FrameWork();
			}
			$this->obj_frameword->setFrameWork();
			$this->obj_frameword->_langType = $langType;
			$this->obj_frameword->getlang("menu");
			
			foreach ($matches as $key => $values){
				$langReplaceString[$key] = preg_replace("|\{lang{$values['1']}\}|U", $this->obj_frameword->_lang["lang{$values['1']}"], $langString);
			}
		}
		if(is_array($langReplaceString)){
			$langString = join($langReplaceString);
		}

		return $langString;
	}
	/**
	 * 整理缩略图
	 *
	 * @param unknown_type $pic
	 * @return unknown
	 */
	function resizePic($pic, $length){
		if (file_exists('../'.$pic) && $pic !=''){

			/*取商品缩略图*/
			if ($pic != ""){
				$line = explode('.',$pic);
				if (file_exists('../'.$line[0].'_small'.'.'.$line[1])){
					$resize_pic_array['small_pic'] = $line[0].'_small'.'.'.$line[1];
				}
				if (file_exists('../'.$line[0].'_mid'.'.'.$line[1])){
					$resize_pic_array['mid_pic'] = $line[0].'_mid'.'.'.$line[1];
				}
				if (file_exists('../'.$line[0].'_big'.'.'.$line[1])){
					$resize_pic_array['big_pic'] = $line[0].'_big'.'.'.$line[1];
				}
				unset($line);
			}

			/*判断缩略图宽高，按比例缩小*/
			$image_array = @getimagesize('../'.$resize_pic_array['small_pic']);
			if ($image_array[0] != 0 && $image_array[1] != 0){
				if ($image_array[0] >= $image_array[1]) {/*宽 > 高*/
					$resize_pic_array['width'] = $length;
					$resize_pic_array['height'] = @number_format($image_array[1]/($image_array[0]/$length),0);
				}else if ($image_array[0] <= $image_array[1]) {
					$resize_pic_array['width'] = @number_format($image_array[0]/($image_array[1]/$length),0);
					$resize_pic_array['height'] = $length;
				}
			}
		}
		return $resize_pic_array;
	}
	
	/**
	 * UTF-8编码转换
	 */
	function utf82u2($str){
	    $len = strlen($str);
	    $start = 0;
	    $result = '';
	
	    if ($len == 0){
	        return $result;
	    }
	
	    while ($start < $len){
	        $num = ord($str{$start});
	        if ($num < 127){
	            $result .= chr($num) . chr($num >> 8);
	            $start += 1;
	        }else{
	            if ($num < 192){
	                /* 无效字节 */
	                $start ++;
	            }elseif ($num < 224){
	                if ($start + 1 <  $len){
	                    $num = (ord($str{$start}) & 0x3f) << 6;
	                    $num += ord($str{$start+1}) & 0x3f;
	                    $result .=   chr($num & 0xff) . chr($num >> 8) ;
	                }
	                $start += 2;
	            }elseif ($num < 240){
	                if ($start + 2 <  $len){
	                    $num = (ord($str{$start}) & 0x1f) << 12;
	                    $num += (ord($str{$start+1}) & 0x3f) << 6;
	                    $num += ord($str{$start+2}) & 0x3f;
	
	                    $result .=   chr($num & 0xff) . chr($num >> 8) ;
	                }
	                $start += 3;
	            }elseif ($num < 248){
	                if ($start + 3 <  $len){
	                    $num = (ord($str{$start}) & 0x0f) << 18;
	                    $num += (ord($str{$start+1}) & 0x3f) << 12;
	                    $num += (ord($str{$start+2}) & 0x3f) << 6;
	                    $num += ord($str{$start+3}) & 0x3f;
	                    $result .= chr($num & 0xff) . chr($num >> 8) . chr($num >>16);
	                }
	                $start += 4;
	            }elseif ($num < 252){
	                if ($start + 4 <  $len){
	                    /* 不做处理 */
	                }
	                $start += 5;
	            }else{
	                if ($start + 5 <  $len){
	                    /* 不做处理 */
	                }
	                $start += 6;
	            }
	        }
	    }
	    return $result;
	}
	
	/**
	 * 取外部链接页面内容
	 * @author workflow Develop Team     
	 * @param  $url 外部链接 $num 循环次数，超过次数返回false
	 * @return string
	 */
	function getUrlContent($url,$num=3){
		$i=0;
		while(!$content or $i==$num){
			$content = @file_get_contents($url);
			$i++;
		}
		if ($content == ''){
			return false;
		}else {
			return $content;
		}
	}
	
	/**
	 * 取IP地址
	 * @author workflow Develop Team     
	 * @param  
	 * @return string
	 */
	function getIP(){
		if(getenv('HTTP_CLIENT_IP') && strcasecmp(getenv('HTTP_CLIENT_IP'), 'unknown')) {
			$ip = getenv('HTTP_CLIENT_IP');
		} elseif(getenv('HTTP_X_FORWARDED_FOR') && strcasecmp(getenv('HTTP_X_FORWARDED_FOR'), 'unknown')) {
			$ip = getenv('HTTP_X_FORWARDED_FOR');
		} elseif(getenv('REMOTE_ADDR') && strcasecmp(getenv('REMOTE_ADDR'), 'unknown')) {
			$ip = getenv('REMOTE_ADDR');
		} elseif(isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], 'unknown')) {
			$ip = $_SERVER['REMOTE_ADDR'];
		}
		return $ip;
	}
	
	/**
	 * unicode转为utf8
	 * @author workflow Develop Team     
	 * @param  
	 * @return string
	 */
	function unicodeToUtf8 ($source)
	{
		$length = strlen($source);
		if ($length & 1){
			return false;
		}
		$str = '';
		for ($i=0; $i < $length; $i+=2){
			$low = ord($source{$i});
			$high = ord($source{$i+1});
			if($high > 8){
				$str .= chr(0xE0 | ($high>>4)) . chr(0x80 | (($high & 0xF) << 2) | ($low >> 6)) . chr(0x80 | ($low & 0x3F));
			}else if ($high == 0 && $low < 128){
				$str .= chr(0x7F & $low);
			}else{
				$str .= chr(0xC0 | (($high & 3) << 2) | ($low >> 6)) . chr(0x80 | ($low & 0x3F));
			}
		}
		return $str;
	}
	
	/**
	 * ut8转码为unicode
	 * @author workflow Develop Team     
	 * @param  
	 * @return string
	 */
	function utf2uni ($str)
	{
		return preg_replace('/([\x00-\x7F]|(?:[\xC0-\xDF][\x80-\xBF])|(?:[\xE0-\xEF][\x80-\xBF][\x80-\xBF])|(?:[\xF0-\xF7][\x80-\xBF][\x80-\xBF][\x80-\xBF])|(?:[\xF8-\xFB][\x80-\xBF][\x80-\xBF][\x80-\xBF][\x80-\xBF])|(?:[\xFC-\xFD][\x80-\xBF][\x80-\xBF][\x80-\xBF][\x80-\xBF][\x80-\xBF]))/e',"Common::en_unicode('\\1')", $str);
	}
	
	function en_unicode($macth){
	    $str = '';
	    $macth = stripslashes($macth);
	    switch(strlen($macth)){
	        case 1:
	            $str =  pack('v', ord($macth));
	            break;
	        case 2:
	            $str = pack('v', ((ord($macth{0}) & 0x1F) << 6) + (ord($macth{1}) & 0x3f));
	            break;
	        case 3:
	            $str = pack('v', ((ord($macth{0}) & 0x1F) << 12) + ((ord($macth{1}) & 0x3f) << 6) + (ord($macth{2}) & 0x3f));
	            break;
	        default :
	    }
	    return $str;
	}
	
	/**
	 * 取地区缓存文件内容
	 * @author workflow Develop Team     
	 * @param  
	 * @return int/bool/object/array
	 */
	function getAreaCache($interval_char='&nbsp;'){
		if (!file_exists(BasePath."/cache/area.php")){
			require_once("area.class.php");
			//重新生成缓存文件
			$obj_area = new AreaClass();
			$result = $obj_area->restartAreaFile();
			if ($result !== true){
				echo BasePath."/cache/area.php is not exist";
				exit;
			}
		}
		require(BasePath."/cache/area.php");//area_cache
		//增加间隔距离
		
		if (is_array($area_cache)){
			foreach ($area_cache as $k => $v){
				//间隔
				$line = $interval_char;
				for ($i=1;$i<$v[4]+2;$i++){
					$line .= $line;
				}
				$area_cache[$k][2] =  $line.$v[2];//
				unset($line);
			}
		}
		return $area_cache;
	}
	
	/**
	 * 转换字符编码
	 *
	 * @param string $content	转换内容
	 * @param string $charset	字符集
	 * @param bool $use_mb	是否使用mb扩展 默认为true 使用
	 * @return array[]
	 */
	function nc_change_charset($content,$charset='',$use_mb=true) {
		if($charset == 'utf-8' or $charset == '') {
			return $content;
		} 
		if($charset == 'utf8_to_gbk' or $charset == 'utf8_to_gb2312') {		//utf8转换为gbk
			return Common::utf8_to_gb2312($content,$use_mb);
		}
		if($charset == 'gbk_to_utf8' or $charset == 'gb2312_to_utf8') {		//gbk转换为utf8
			return Common::gb2312_to_utf8($content,$use_mb);
		}
		if ($charset == 'utf8_to_big5') {	//utf8转换为big5
			return Common::utf8_to_big5($content,$use_mb);
		}
		if($charset == 'big5_to_utf8') {	//big转换为utf8
			return Common::big5_to_utf8($content,$use_mb);
		}
		if($charset == 'gbk_to_big5' or $charset == 'gb2312_to_big5') {		//gbk转换为big5
			return Common::gb2312_to_big5($content,$use_mb);
		}
		if($charset == 'big5_to_gbk' or $charset == 'big5_to_gb2312') {		//big转换为gbk
			return Common::big5_to_gb2312($content,$use_mb);
		}
	}
	/**
	 * utf-8转gb2312
	 *
	 * @param string $content	转换内容
	 * @return string
	 */
	function utf8_to_gb2312( $content,$use_mb ) {
		if(function_exists('mb_convert_encoding') && $use_mb == true) {
			return mb_convert_encoding($content,'gb2312','utf-8');
		}
		$fp = fopen(BasePath.'/classes/libraries/encode/utf8-gb.tab', 'r' );
		$len = strlen($content);
		$outstr = '';
		for( $i = $x = 0 ; $i < $len ; $i++ ) {
			$b1 = ord($content[$i]);
			if( $b1 < 0x80 ) {
				$outstr[$x++] = chr($b1);
			}
			elseif( $b1 >= 224 ) {
				$b1 -= 224;
				$b2 = ($i+1 >= $len) ? 0 : ord($content[$i+1]) - 128;
				$b3 = ($i+2 >= $len) ? 0 : ord($content[$i+2]) - 128;
				$i += 2;
				$uc = $b1 * 4096 + $b2 * 64 + $b3 ;
				fseek( $fp, $uc * 2 );
				$gb = fread( $fp, 2 );
				$outstr[$x++] = $gb[0];
				$outstr[$x++] = $gb[1];
			}
			elseif( $b1 >= 192 ) {
				printf( "[%02X%02X]", $b1, ord($content[$i+1]) );
				$b1 -= 192;
				$b2 = ($i+1>=$len) ? 0 : ord($content[$i+1]) - 128;
				$i++;
				$uc = $b1 * 64 + $b2 ;
				fseek( $fp, $uc * 2 );
				$gb = fread( $fp, 2 );
				$outstr[$x++] = $gb[0];
				$outstr[$x++] = $gb[1];
			}
		}
		fclose($fp);
		if( $content != '' ) {
			return join( '', $outstr);
		}
	}
	/**
	 * gb2312转utf-8
	 *
	 * @param string $content	转换内容
	 * @return string
	 */
	function gb2312_to_utf8( $content,$use_mb ) {
//		if(function_exists('mb_convert_encoding')) {
//			return mb_convert_encoding($content,'utf-8','gb2312');
//		}
		$fp = fopen(BasePath.'/classes/libraries/encode/gb-utf8.tab', 'r' );
		$len = strlen($content);
		$outstr = '';
		for( $i = $x = 0 ; $i < $len ; $i++ ) {
			$h = ord($content[$i]);
			if( $h > 160 ) {
				$l = ( $i+1 >= $len ) ? 32 : ord($content[$i+1]);
				fseek( $fp, ($h-161)*188+($l-161)*2 );
				$uni = fread( $fp, 2 );
				$codenum = ord($uni[0])*256 + ord($uni[1]);
				if( $codenum < 0x800 ) {
					$outstr[$x++] = chr( 192 + $codenum / 64 );
					$outstr[$x++] = chr( 128 + $codenum % 64 );
				}
				else {
					$outstr[$x++] = chr( 224 + $codenum / 4096 );
					$codenum %= 4096;
					$outstr[$x++] = chr( 128 + $codenum / 64 );
					$outstr[$x++] = chr( 128 + ($codenum % 64) );
				}
				$i++;
			}
			else
			$outstr[$x++] = $content[$i];
		}
		fclose($fp);
		if( $content != '' )
		return join( '', $outstr);
	}
	/**
	 * big5转gb
	 *
	 * @param string $content	转换内容
	 * @return string
	 */
	function big5_to_gb2312( $content,$use_mb ) {
		if(function_exists('mb_convert_encoding') && $use_mb == true) {
			return mb_convert_encoding($content,'gb2312','big5');
		}
		
		$fp = fopen(BasePath.'/classes/libraries/encode/big5-gb.tab', 'r' );

		$len = strlen($content);
		for( $i = 0 ; $i < $len ; $i++ ) {
			$h = ord($content[$i]);
			if( $h >= 160 ) {
				$l = ($i+1 >= $len) ? 32 : ord($content[$i+1]);
				if( $h == 161 && $l == 64 )
				$gb = '  ';
				else {
					fseek( $fp, (($h-160)*255+$l-1)*3 );
					$gb = fread( $fp, 2 );
				}
				$content[$i] = $gb[0];
				$content[$i+1] = $gb[1];
				$i++;
			}
		}
		fclose($fp);
		return $content;
	}
	/**
	 * gb转bg
	 *
	 * @param string $content	转换内容
	 * @return string
	 */
	function gb2312_to_big5( $content,$use_mb ) {
		if(function_exists('mb_convert_encoding') && $use_mb == true) {
			return mb_convert_encoding($content,'big5','gb2312');
		}
		$fp = fopen(BasePath.'/classes/libraries/encode/gb-big5.tab', 'r' );

		$len = strlen($content);
		for( $i = 0 ; $i < $len ; $i++ ) {
			$h = ord($content[$i]);
			if( $h > 160 && $h < 248 ) {
				$l = ($i+1 >= $len) ? 32 : ord($content[$i+1]);
				if( $l > 160 && $l < 255 ) {
					fseek( $fp, (($h-161)*94+$l-161)*3 );
					$bg = fread( $fp, 2 );
				}
				else
				$bg = '  ';
				$content[$i] = $bg[0];
				$content[$i+1] = $bg[1];
				$i++;
			}
		}
		fclose($fp);
		return $content;
	}
	/**
	 * big5转utf-8
	 *
	 * @param string $content	转换内容
	 * @return string
	 */
	function big5_to_utf8( $content,$use_mb ) {
		if(function_exists('mb_convert_encoding') && $use_mb == true) {
			return mb_convert_encoding($content,'gb2312','utf-8');
		}
		$fp = fopen(BasePath.'/classes/libraries/encode/big5-utf8.tab', 'r' );
		$len = strlen($content);
		$outstr = '';
		for( $i = $x = 0 ; $i < $len ; $i++ ) {
			$h = ord($content[$i]);
			if( $h >= 160 ) {
				$l = ( $i+1 >= $len ) ? 32 : ord($content[$i+1]);
				if( $h == 161 && $l == 64 )
				$uni = '  ';
				else {
					fseek( $fp, ($h-160)*510+($l-1)*2 );
					$uni = fread( $fp, 2 );
				}
				$codenum = ord($uni[0])*256 + ord($uni[1]);
				if( $codenum < 0x800 ) {
					$outstr[$x++] = chr( 192 + $codenum / 64 );
					$outstr[$x++] = chr( 128 + $codenum % 64 );
				}
				else {
					$outstr[$x++] = chr( 224 + $codenum / 4096 );
					$codenum %= 4096;
					$outstr[$x++] = chr( 128 + $codenum / 64 );
					$outstr[$x++] = chr( 128 + ($codenum % 64) );
				}
				$i++;
			}
			else
			$outstr[$x++] = $content[$i];
		}
		fclose($fp);
		if( $content != '' )
		return join( '', $outstr);
	}
	/**
	 * utf-8转big5
	 *
	 * @param string $content	转换内容
	 * @return string
	 */
	function utf8_to_big5( $content,$use_mb ) {
		if(function_exists('mb_convert_encoding') && $use_mb == true) {
			return mb_convert_encoding($content,'big5','utf-8');
		}
		$fp = fopen(BasePath.'/classes/libraries/encode/utf8-big5.tab', 'r' );
		$len = strlen($content);
		$outstr = '';
		for( $i = $x = 0 ; $i < $len ; $i++ ) {
			$b1 = ord($content[$i]);
			if( $b1 < 0x80 ) {
				$outstr[$x++] = chr($b1);
			}
			elseif( $b1 >= 224 ) {
				$b1 -= 224;
				$b2 = ord($content[$i+1]) - 128;
				$b3 = ord($content[$i+2]) - 128;
				$i += 2;
				$uc = $b1 * 4096 + $b2 * 64 + $b3 ;
				fseek( $fp, $uc * 2 );
				$bg = fread( $fp, 2 );
				$outstr[$x++] = $bg[0];
				$outstr[$x++] = $bg[1];
			}
			elseif( $b1 >= 192 ) {
				printf( "[%02X%02X]", $b1, ord($content[$i+1]) );
				$b1 -= 192;
				$b2 = ord($content[$i]) - 128;
				$i++;
				$uc = $b1 * 64 + $b2 ;
				fseek( $fp, $uc * 2 );
				$bg = fread( $fp, 2 );
				$outstr[$x++] = $bg[0];
				$outstr[$x++] = $bg[1];
			}
		}
		fclose($fp);
		if( $content != '' ) {
			return join( '', $outstr);
		}
	}
	
	/**
	 * 取商品品牌缓存文件内容
	 * @author workflow Develop Team     
	 * @param  
	 * @return array
	 */
	function getProductBrandCache($interval_char='&nbsp;'){
		if (!file_exists(BasePath."/cache/product_brand.php")){
			require_once("product_brand.class.php");
			//重新生成缓存文件
			$obj_product_brand = new ProductBrandClass();
			$result = $obj_product_brand->restartProductBrand();
			if ($result !== true){
				echo BasePath."/cache/product_brand.php is not exist";
				exit;
			}
		}
		require(BasePath."/cache/product_brand.php");//area_cache
		//增加间隔距离
		if (is_array($product_brand_cache)){
			foreach ($product_brand_cache as $k => $v){
				//间隔
				$line = $interval_char;
				for ($i=1;$i<$v[4]+2;$i++){
					$line .= $line;
				}
				$product_brand_cache[$k][2] =  $line.$v[2];//
				unset($line);
			}
		}
		return $product_brand_cache;
	}
}
?>
